package com.maoslv.service.role;

import com.maoslv.mapper.MenuMapper;
import com.maoslv.mapper.RoleMapper;
import com.maoslv.pojo.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    MenuMapper menuMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String,Object> getRoleList(Map<String,Object> map) {
        List<Role> roleList = roleMapper.getRoleList(map);
        Integer total = roleMapper.getTotal(map);
        Map<String,Object> result = new HashMap<>();
        result.put("roleList", roleList);
        result.put("total", total);
        return result;
    }

    @Override
    public int updateRole(Map<String, Object> roleMap) {
        return roleMapper.updateRole(roleMap);
    }

    @Override
    public Role getRoleInfo(Integer id) {
        return roleMapper.getRoleInfo(id);
    }

    @Override
    public int delRole(Integer id) {
        return roleMapper.delRole(id);
    }

    @Override
    public int addRole(Map<String,Object> roleMap) {
        return roleMapper.addRole(roleMap);
    }

    @Override
    public int updatePerms(Integer id, List<Integer> menuIds) {
        List<Integer> menuListById = menuMapper.getMenuListById(id);
        if (menuListById.size() > menuIds.size()) {
            menuListById.removeAll(menuIds);
            return roleMapper.delPerms(id,menuListById);
        } else if (menuListById.size() < menuIds.size()) {
            menuIds.removeAll(menuListById);
            return roleMapper.addPerms(id,menuIds);
        } else {
            return 1;
        }
    }
}
